package main

import (
	"context"
	"fmt"
	"github.com/golang/protobuf/ptypes/timestamp"
	"google.golang.org/grpc"
	"grpc_cli/helper"
	. "grpc_cli/services"
	"io"
	"log"
	"time"
)

func main(){

	conn,err := grpc.Dial(":8088",grpc.WithTransportCredentials(helper.GetClientCreds()))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	prodClient := NewProdServiceClient(conn)
	ctx := context.Background()
	//获取单个商品库存,指定区域
	//prodRes,err := prodClient.GetProdStock(ctx,&ProdRequest{ProdId: 12,ProdArea: ProdAreas_C})
	prod,err := prodClient.GetProdInfo(ctx,&ProdRequest{ProdId: 12})//导入外部proto,获取商品信息

	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(prod.ProdName)

	//获取多个商品库存
	//response,err := prodClient.GetProdStocks(ctx,&services.QuerySize{Size: 10})
	//if err != nil {
	//	log.Fatal(err)
	//}
	//fmt.Println(response.Prodres)

	orderClient := NewOrderServiceClient(conn)
	t := timestamp.Timestamp{Seconds: time.Now().Unix()}
	order,OrderErr := orderClient.NewOrder(ctx,&OrderMain{
		OrderId: 1,
		OrderNo: "20210913",
		UserId: 123,
		OrderMoney: 98,
		OrderTime: &t,
	})
	if OrderErr != nil {
		log.Fatal(OrderErr)
	}
	fmt.Printf("订单状态：%s\n订单信息：%s\n",order.Status,order.Message)

	userClient := NewUserServiceClient(conn)
	var i int32

	//stream,err := userClient.GetUserScoreByClientStream(ctx)//客户端流模式获取积分
	stream,err := userClient.GetUserScoreByTWS(ctx)//双向流模式获取用户积分
	if err != nil {
		log.Fatal(err)
	}

	var uid int32 = 1
	for j := 1;j <= 3;j++{//分批发送数据，模拟数据量大的情况
		req := UserScoreRequest{}
		req.Users = make([]*UserInfo,0)

		for i = 1;i < 6;i++ {//添加5条用户信息
			req.Users = append(req.Users,&UserInfo{UserId: uid})
			uid++
		}
		err := stream.Send(&req)
		if err != nil {
			log.Println(err)
		}
		res,err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Println(err)
		}
		fmt.Println(res.Users)
	}

	//res,_ := stream.CloseAndRecv()
	//fmt.Println(res.Users)

	//res,err := userClient.GetUserScore(ctx,&req)普通获取用户积分
	//stream,err := userClient.GetUserScoreByServerStream(ctx,&req)服务端流模式获取用户积分
	//if err != nil {
	//	log.Fatal(err)
	//}
	//for{
	//	res,err := stream.Recv()
	//	if err == io.EOF{
	//		break
	//	}
	//	if err != nil {
	//		log.Fatal(err)
	//	}
	//	fmt.Println(res.Users)
	//}



}
